#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
class Solution {
public:
    long long minimumCost(int m, int n, vector<int>& horizontalCut, vector<int>& verticalCut) {
        sort(horizontalCut.begin(), horizontalCut.end(), greater<int>());
        sort(verticalCut.begin(), verticalCut.end(), greater<int>());
        int i = 0, j = 0;
        long long ans = 0;
        while (i < m - 1 || j < n - 1) {
            if (i < m - 1 && j < n - 1) {
                if (horizontalCut[i] > verticalCut[j])
                    ans += horizontalCut[i++] * (j + 1);
                else
                    ans += verticalCut[j++] * (i + 1);
            }
            else if (i < m - 1)
                ans += horizontalCut[i++] * (j + 1);
            else
                ans += verticalCut[j++] * (i + 1);
        }
        return ans;
    }
};